package cn.ymatrix.jdbcToYMatrix;

import cn.ymatrix.logger.LoggerLevel;
import cn.ymatrix.logger.MxLogger;
import cn.ymatrix.utils.Config;
import cn.ymatrix.utils.DataUtil;
import org.slf4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCBatchTOYMatrix {

  public static void main(String[] args) {

    MxLogger.loggerLevel(LoggerLevel.INFO);
    Logger LOGGER = MxLogger.init(JDBCBatchTOYMatrix.class);

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    int batchSize = Config.getBatchSize();
    int totalNumber = Config.getTotalNumber();
    try {
      connection = Config.getDateSource().getConnection();
      connection.setAutoCommit(false);
      LOGGER.info("---- 开始插入数据 ----");
      long startTime = System.currentTimeMillis();
      String sqlInsert = getSQLInsertStr();
      preparedStatement = connection.prepareStatement(sqlInsert);
      preparedStatement.setFetchSize(10);
      for (int i = 1; i <= totalNumber; i++) {
        preparedStatement.setTimestamp(1, DataUtil.getCurrentTimestamp());
        for (int j = 2; j <= 6; j++) {
          preparedStatement.setInt(j, DataUtil.getIntValue());
        }
        preparedStatement.addBatch();
        preparedStatement.executeBatch();
        if (i % batchSize == 0) {
          connection.commit();
          LOGGER.info("成功插入第 " + i + " 条数据");
        }
      }
      preparedStatement.executeBatch();
      connection.commit();
      long spendTime = System.currentTimeMillis() - startTime;
      LOGGER.info("成功插入 " + totalNumber + " 条数据,耗时: " + spendTime + "毫秒");
    } catch (SQLException e) {
      LOGGER.error("SQLException Error: " + e.getMessage());
    } finally {
      if (preparedStatement != null) {
        try {
          preparedStatement.close();
        } catch (SQLException e) {
          LOGGER.error("preparedStatement close error " + e.getMessage());
          e.printStackTrace();
        }
      }
      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e) {
          LOGGER.error("connection close  error " + e.getMessage());
          e.printStackTrace();
        }
      }
    }
  }

  public static String getSQLInsertStr() {
    StringBuilder sqlInsert =
        new StringBuilder("INSERT INTO " + Config.getTableName() + "(ts,vin,");
    for (int i = 1; i <= 4; i++) {
      sqlInsert.append("t" + i + ",");
    }
    sqlInsert.deleteCharAt(sqlInsert.length() - 1).toString();
    sqlInsert.append(") VALUES (");
    for (int i = 1; i <= 6; i++) {
      sqlInsert.append("?,");
    }
    return sqlInsert.deleteCharAt(sqlInsert.length() - 1) + ")";
  }
}
